package sisi.bank;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;


/**
 * BankWindow.java - Controller class for <i>Bank window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 20/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class BankWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxBank
	private Window windowBank, windowEditBank;
	private Textbox tbCerca;
	private Listbox boxBank;

	private List tutti_i_bank;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object bankItem;
	private Bank modBank;
	// edit
	private Intbox id;
	private Textbox address, city, cceuro, bank, ibaneur, ccusd, ibanusd, swft, cap;

	public void onCreate$windowBank(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutti_i_bank = new BankController().getBankList(null);
		listModelList.addAll(tutti_i_bank);
		boxBank.setModel(listModelList);
		boxBank.setItemRenderer(new BankItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutti_i_bank.size(); i++) {
				Bank bank = (Bank)tutti_i_bank.get(i);
				if (bank.getId()==idSelezionato.intValue()){
					boxBank.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutti_i_bank = new BankController().getBankList(tbCerca
				.getValue());
		listModelList.addAll(tutti_i_bank);
		boxBank.setModel(listModelList);
		boxBank.setItemRenderer(new BankItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		seleziona();

	}

	public void seleziona() {
		if (boxBank.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oBank = boxBank.getSelectedItem().getAttribute(
					"rigaBank");
			String codiceSelezionato = ""+((Bank) oBank).getId();
			Sessions.getCurrent().setAttribute("codiceBankSelezionato",
					codiceSelezionato);
			windowBank.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxBank.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Bank to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxBank", boxBank);
				Window finestraEditBank = (Window) Executions.createComponents(
						"/editBank.zul", null, map);
				finestraEditBank.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class BankItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Bank) data).getId()).setParent(li);
			new Listcell(((Bank) data).getBank()).setParent(li);
			li.setAttribute("rigaBank", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT BANK: NEW/MODIFY
	public void onCreate$windowEditBank(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxBank = (Listbox) args.get("boxBank");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			bankItem = boxBank.getSelectedItem().getAttribute("rigaBank");
			modBank = new BankController().refreshBank((Bank) bankItem);
			bankItem = modBank;
			windowEditBank.setTitle("Edit Bank");
			bank.setFocus(true);
			id.setValue(modBank.getId());
			bank.setValue(General.toUpperAncheNull(modBank.getBank()));
			address.setValue(General.toUpperAncheNull(modBank.getAddress()));
			cap.setValue(modBank.getCap());
			city.setValue(General.toUpperAncheNull(modBank.getCity()));
			cceuro.setValue(General.toUpperAncheNull(modBank.getCceuro()));
			ibaneur.setValue(General.toUpperAncheNull(modBank.getIbaneur()));
			ccusd.setValue(modBank.getCcusd());
			ibanusd.setValue(General.toUpperAncheNull(modBank.getIbanusd()));
			swft.setValue(General.toUpperAncheNull(modBank.getSwft()));
		} else {
			windowEditBank.setTitle("New Bank");
			bank.setFocus(true);
		}
	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditBank.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modBank = new Bank();
		} else {

		}
		String testoMsg = "";
		
		modBank.setId(id.getValue());
		modBank.setBank(General.toUpperAncheNull(bank.getValue()));
		modBank.setAddress(General.toUpperAncheNull(address.getValue()));
		modBank.setCap(cap.getValue());
		modBank.setCceuro(cceuro.getValue());
		modBank.setCcusd(ccusd.getValue());
		modBank.setCity(General.toUpperAncheNull(city.getValue()));
		modBank.setIbaneur(General.toUpperAncheNull(ibaneur.getValue()));
		modBank.setIbanusd(General.toUpperAncheNull(ibanusd.getValue()));
		modBank.setSwft(General.toUpperAncheNull(swft.getValue()));	
		if (lNuovo){
			new BankController().addBank(modBank);
			testoMsg = "Adding Bank: "+ General.trimNull( modBank.getBank() );
		} else {
			new BankController().updateBank(modBank);
			testoMsg = "Updating Bank: "+ General.trimNull( modBank.getBank() );			
		}
		
		General.showNotify( testoMsg, windowEditBank);
		
		windowEditBank.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxBank.getListModel();
			lml.add(modBank);
			boxBank.setSelectedIndex(lml.indexOf(modBank));
		} else {
			ListModelList lml = (ListModelList) boxBank.getListModel();
			Object oBankItem = boxBank.getSelectedItem().getAttribute("rigaBank");
			if (lml.indexOf(oBankItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oBankItem), modBank);
			}
		}		
	}
	
	
}
